package com.example.enews.adapters

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.example.enews.databinding.ItemRankBinding
import com.example.enews.models.RankItem
import com.example.enews.models.RegionPriority

class RankAdapter : RecyclerView.Adapter<RankAdapter.ViewHolder>() {

    private var dataList: List<RankItem> = emptyList()

    inner class ViewHolder(val binding: ItemRankBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(item: RankItem) {
            binding.tvTeam.text = item.teamName
            binding.tvRegion.text = item.region
            binding.tvScore.text = item.score.toString()
            binding.tvRank.text = item.rank.toString()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemRankBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(dataList[position])
    }

    override fun getItemCount(): Int = dataList.size

    fun submitList(list: List<RankItem>) {
        dataList = list.sortedWith(
            compareByDescending<RankItem> { it.score }
                .thenBy { RegionPriority.getPriority(it.region) }
        )
        notifyDataSetChanged()
    }
}

